package com.atguigu.crowd.funding.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 工具类
 * @author Administrator
 *
 */
public class CorwdUtil {

	//16进制，主要为了十转十六
	static char[] c16={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	
	
	/**
	 * 判断是否是异步请求
	 * @param request
	 * @return
	 */
	public static boolean isAsyncRequest(HttpServletRequest request){
		//1。获取请求头
		String accept = request.getHeader("Accept");
		String xRequest = request.getHeader("X-Requested-With");
		//2.判断请求消息头数据中是否包含目标特征
		if(
			(StringEff(accept)&&accept.contains("application/json"))||
			(StringEff(xRequest)&&accept.contains("XMLHttpRequest"))
			){
			return true;
		}
		return false;
	}
	
	/**
	 * map是否有效判断方法
	 * null�򷵻�false
	 */
	public static <E,T> boolean MapEff(Map<E,T> map){
		return map!=null&&map.size()>0;
	}
	
	 
	/**
	 * 集合是否有效判断方法
	 * ��null�򷵻�false
	 * @param <E>
	 */
	public static <E> boolean CollectionEff(Collection<E> conllection){
		return conllection!=null&&conllection.size()>0;
	}
	
	/**
	 * 字符串是否有效
	 * null=false
	 */
	public static boolean StringEff(String str){
		return str!=null&&str.length()>0;
	}
	/**
	 * md5加密
	 * @return
	 */
	public static String md5(String srouce){
		StringBuffer str=new StringBuffer();//�洢���ܺ��hashֵ
		byte[] mdbyte=null;					//���md5���ܺ�δת��Ϊhashֵ���ֽ�
		
		//�ж��ַ��Ƿ�ǿ�,�����null�׳��쳣
		if(!StringEff(srouce)){
			throw new RuntimeException(CrowdFundingConstant.MESSAGE_CODE_INVALID);
		}
		
		//����
		try {
			//��ȡһ��md5����ժҪ�����ģ�
			MessageDigest md = MessageDigest.getInstance("MD5");
			
			//���ܻ�ü��ܺ���ֽ�����
			mdbyte = md.digest(srouce.getBytes());
			
			//�����ܺ���ֽ�����תΪ16���Ƶ�hashֵ
			for(int i = 0;i < mdbyte.length;i++){
				
				/*1����ȡÿ���ֽڵĵ���λֵ�����λ��10����ֵ
				 * ����λ��һ���ֽ�8λ����ԭ�ֽڸ�00001111��15����������ɵó�����ԭ�ֽڣ�10101101 & 00001111=00001101=13
				 * ����λ����ԭ�ֽ�������λ�ٸ�00001111��������ɵã���(10101101>>4) & 00001111=00001010=10
				 */
				int lowdate = mdbyte[i] & 15;
				int higdate = (mdbyte[i] >> 4) & 15;
				
				/*
				 * 2���õ���10����ֵ��16����������ڣ��൱���±꣩��16����ֵ
				 * ��������ַ����� 
				 */
				str.append(c16[higdate]).append(c16[lowdate]);
			}
			
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return str.toString();
	}
}
